<template>
    <div class="app-container">
      <!-- 头部 -->
      <div class="header">
        <div>API接口管理</div>
        <el-button type="primary" icon="el-icon-plus" @click="openAddDialog" size="mini">新增API</el-button>
      </div>
      <!-- 搜索区域 -->
      <!-- <div class="search-bar">
        <el-input
          placeholder="请输入API类型、URL或描述"
          v-model="searchKeyword"
          @keyup.enter.native="filterApis"
          clearable
          @clear="filterApis"
        >
          <el-button slot="append" icon="el-icon-search" @click="filterApis"></el-button>
        </el-input>
      </div> -->
      
      <!-- API表格 -->
      <el-table
        v-loading="loading"
        :data="filteredApis"
        style="width: 100%"
      >
        <el-table-column label="接口名称" >
          <template slot-scope="scope">
            <div class="api-title">{{ scope.row.apiName }}</div>
            <!-- <div class="api-header">
              <div class="api-icon">
                <i class="fas fa-plug"></i>
              </div>
              <div>
                <div class="api-title">{{ scope.row.apiName }}</div>
                <div class="api-meta">
                  <div class="api-meta-item">
                    <i class="el-icon-time"></i>
                    <span>{{ formatDate(scope.row.createdAt) }}</span>
                  </div>
                  <div class="api-meta-item">
                    <i class="el-icon-refresh"></i>
                    <span>{{ formatDate(scope.row.updatedAt) }}</span>
                  </div>
                </div>
              </div>
            </div>
           <div class="api-description">{{ scope.row.description || '暂无描述' }}</div> -->
          </template>
        </el-table-column> 
        
        <el-table-column label="API类型" width="220" align="center">
          <template slot-scope="scope">
            <span class="api-type-badge" :class="'api-type-' + scope.row.apiType.toLowerCase()">
              {{ scope.row.apiType }}
            </span>
          </template>
        </el-table-column>
        <el-table-column label="apiAuthId" min-width="200" prop="apiAuthId"></el-table-column>
        <el-table-column label="URL" min-width="160">
          <template slot-scope="scope">
            <div class="api-url">{{ scope.row.apiUrl }}</div>
          </template>
        </el-table-column>
        
        <el-table-column label="关联项目" width="140">
          <template slot-scope="scope">
            <div v-if="scope.row.projects && scope.row.projects.length > 0" class="project-tags">
              <el-tag v-for="proj in scope.row.projects" :key="proj.id" size="small" type="primary">
                {{ proj.projectName }}
              </el-tag>
            </div>
            <span v-else>-</span>
          </template>
        </el-table-column>
        
        <el-table-column label="操作" width="180" align="center" fixed="right">
          <template slot-scope="scope">
            <div class="operation-cell">
              <el-button type="primary" size="mini" icon="el-icon-edit" @click="openEditDialog(scope.row)">编辑</el-button>
              <el-button type="danger" size="mini" icon="el-icon-delete" @click="confirmDelete(scope.row)">删除</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 无数据提示 -->
      <div v-if="filteredApis.length === 0 && !loading" class="no-data">
        <i class="fas fa-inbox"></i>
        <p>没有找到匹配的API接口</p>
      </div>
      
      <!-- 新增/编辑对话框 -->
      <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="800px">
        <el-form :model="form" :rules="rules" ref="form" label-width="100px">
          <div class="form-section">
            <div class="form-section-title">
              <i class="fas fa-info-circle"></i> API基本信息
            </div>
            <el-form-item label="API名称" prop="apiName">
              <el-input v-model="form.apiName" placeholder="请输入API名称"></el-input>
            </el-form-item>
            
            <el-form-item label="API类型" prop="apiType">
              <el-select v-model="form.apiType" placeholder="请选择API类型" style="width: 100%">
                <el-option
                  v-for="item in listAllType"
                  :key="item"
                  :label="item"
                  :value="item">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="ApiAuthId" prop="apiAuthId">
              <el-input v-model="form.apiAuthId" placeholder="请输入ApiAuthId"></el-input>
            </el-form-item>
            <el-form-item label="API URL" prop="apiUrl">
              <el-input v-model="form.apiUrl" placeholder="请输入API URL"></el-input>
            </el-form-item>
            
            <!-- <el-form-item label="API描述">
              <el-input 
                type="textarea" 
                v-model="form.description" 
                placeholder="请输入API描述"
                :autosize="{ minRows: 3, maxRows: 5 }"
              ></el-input>
            </el-form-item> -->
          </div>
          
          <div class="form-section">
            <div class="form-section-title">
              <i class="fas fa-project-diagram"></i> 关联项目
            </div>
            <div class="project-tree">
              <el-tree
                ref="projectTree"
                :data="allProjects"
                show-checkbox
                node-key="id"
                :props="projectTreeProps"
                :default-expand-all="true"
                :check-strictly="true"
                :default-checked-keys="form.projectIds"
              ></el-tree>
            </div>
          </div>
        </el-form>
        
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitForm">确 定</el-button>
        </span>
      </el-dialog>
    </div>
</template>
<script>




export default {
  name: 'Program',  
  components: { },
  props: {

  },
  data(){
    return{
      loading: false,
          searchKeyword: '',
          apis: [],
          filteredApis: [],
          dialogVisible: false,
          dialogTitle: '新增API',
          form: {
            id: null,
            apiAuthId: '',
            apiName:'',
            apiType: '',
            apiUrl: '',
            projectIds: []
          },
          rules: {
            apiName: [
              { required: true, message: '请输入apiName', trigger: 'blur' },
              { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
            ],
            apiAuthId: [
              { required: true, message: '请输入apiAuthId', trigger: 'blur' },
              { min: 3, max: 100, message: '长度在 3 到 100 个字符', trigger: 'blur' }
            ],
            apiType: [
              { required: true, message: '请选择API类型', trigger: 'change' }
            ],
            apiUrl: [
              { required: true, message: '请输入API URL', trigger: 'blur' },
              { max: 500, message: 'URL不能超过500个字符', trigger: 'blur' }
            ]
          },
          allProjects: [],
          listAllType: [],
          projectTreeProps: {
            label: 'projectName',
            children: 'children'
          }
    }
  },
  mounted() {
        this.fetchData();
        this.getProject();
        this.getType();
      },
      methods: {
        getType(){
          this.$axios.get('/api/services/hzsfjtai/api/listAllType', {}).then(res => {
                  if (res.data.code === 200) {
                    this.listAllType =res.data.data
                  } else {
                    this.$message(res.data.msg)
                  }
                }).catch(err => {
                  this.$message.error(err)
                })
        },
         getProject(){
            this.$axios.get('/api/services/hzsfjtai/project/treeList', {}).then(res => {
                  if (res.data.code === 200) {
                    this.allProjects =res.data.data.map(item => ({
                      ...item,
                      parentId: item.value == null ? 0 : item.value
                    }));
                    console.log(89,this.allProjects);
                  } else {
                    this.$message(res.data.msg)
                  }
                }).catch(err => {
                  this.$message.error(err)
                })
          },
        // 获取数据
        fetchData() {
          // this.loading = true;
          this.$axios.get('/api/services/hzsfjtai/api/listAll', {}).then(res => {
              if (res.data.code === 200) {
                this.apis =res.data.data;
                 this.filteredApis = [...this.apis];
                // this.loading = false;
              } else {
                this.$message(res.data.msg)
              }
            }).catch(err => {
              this.$message.error(err)
            })
        },
        
        // 打开新增对话框
        openAddDialog() {
          this.dialogTitle = '新增API';
          this.form = {
            id: null,
            apiName: '',
            apiType: '',
            apiAuthId:'',
            apiUrl: '',
            projectIds: []
          };
          this.dialogVisible = true;
          this.$nextTick(() => {
            if (this.$refs.projectTree) {
              this.$refs.projectTree.setCheckedKeys([]);
            }
            if (this.$refs.form) {
              this.$refs.form.clearValidate();
            }
          });
        },
        
        // 打开编辑对话框
        openEditDialog(api) {
          this.dialogTitle = '编辑API';
          this.form = {
            id: api.id,
            apiAuthId: api.apiAuthId,
            apiName: api.apiName,
            apiType: api.apiType,
            apiUrl: api.apiUrl,
            projectIds: api.projects.map(pro => pro.id) || []
          };
          this.dialogVisible = true;
          this.$nextTick(() => {
            if (this.$refs.projectTree) {
              this.$refs.projectTree.setCheckedKeys( api.projects.map(pro => pro.id) || []);
            }
            if (this.$refs.form) {
              this.$refs.form.clearValidate();
            }
          });
        },
        
        // 提交表单
        submitForm() {
          this.$refs.form.validate(valid => {
            if (valid) {
              // 获取选中的项目ID
              const checkedKeys = this.$refs.projectTree.getCheckedKeys();
              const halfCheckedKeys = this.$refs.projectTree.getHalfCheckedKeys();
              const projectIds = [...checkedKeys, ...halfCheckedKeys];
              
              // 添加到表单数据
              this.form.projectIds = projectIds;
              
              if (this.form.id) {
                // 更新API
                this.updateApi();
              } else {
                // 新增API
                this.addApi();
              }
              this.dialogVisible = false;
            }
          });
        },
        
        // 新增API
        addApi() {
          // const newApi = {
          //   id: this.generateId(),
          //   apiName: this.form.apiName,
          //   apiType: this.form.apiType,
          //   apiUrl: this.form.apiUrl,
          //   description: this.form.description,
          //   createdAt: new Date().toISOString(),
          //   updatedAt: new Date().toISOString(),
          //   projectIds: this.form.projectIds,
          //   projects: this.getProjectsByIds(this.form.projectIds)
          // };
          this.$axios.post('/api/services/hzsfjtai/api/add', {
            apiName: this.form.apiName,
            apiType: this.form.apiType,
            apiUrl: this.form.apiUrl,
            apiAuthId: this.form.apiAuthId,
            createdAt: new Date().toISOString(),
            updatedAt: new Date().toISOString(),
           projects: this.getProjectsByIds(this.form.projectIds)
          }).then(res => {
            if (res.data.code === 200) {
              this.fetchData();
              this.$message({
                type: 'success',
                message: 'api添加成功!'
              });
            } else {
              this.$message(res.data.msg)
            }
          }).catch(err => {
            this.$message.error(err)
          })
        },
        
        // 更新API
        updateApi() {
          const index = this.apis.findIndex(a => a.id === this.form.id);
          if (index !== -1) {
            // this.apis[index] = {
            //   ...this.apis[index],
            //   apiName: this.form.apiName,
            //   apiType: this.form.apiType,
            //   apiUrl: this.form.apiUrl,
            //   description: this.form.description,
            //   updatedAt: new Date().toISOString(),
            //   projectIds: this.form.projectIds,
            //   projects: this.getProjectsByIds(this.form.projectIds)
            // };
            
            // this.filteredApis = [...this.apis];
            
            // this.$message({
            //   type: 'success',
            //   message: 'API更新成功!'
            // });
            this.$axios.post('/api/services/hzsfjtai/api/update', {
              id:this.form.id,
              apiName: this.form.apiName,
              apiType: this.form.apiType,
              apiUrl: this.form.apiUrl,
              apiAuthId: this.form.apiAuthId,
              createdAt: new Date().toISOString(),
              updatedAt: new Date().toISOString(),
              projects: this.getProjectsByIds(this.form.projectIds)
            }).then(res => {
              if (res.data.code === 200) {
                this.fetchData();
                this.$message({
                  type: 'success',
                  message: 'api更新成功!'
                });
              } else {
                this.$message(res.data.msg)
              }
            }).catch(err => {
              this.$message.error(err)
            })
          }
        },
        
        // 根据ID获取项目信息
        getProjectsByIds(ids) {
          const projects = [];
          this.traverseProjects(this.allProjects, node => {
            if (ids.includes(node.id)) {
              projects.push({
                id: node.id,
                projectName: node.projectName,
                description: node.description || '',
                parentId: node.parentId
              });
            }
          });
          return projects;
        },
        
        // 遍历项目树
        traverseProjects(nodes, callback) {
          nodes.forEach(node => {
            callback(node);
            if (node.children && node.children.length) {
              this.traverseProjects(node.children, callback);
            }
          });
        },
        
        // 确认删除
        confirmDelete(api) {
          this.$confirm(`确定删除API接口吗?`, '删除确认', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            this.deleteApi(api.id);
          }).catch(() => {});
        },
        // 删除API
        deleteApi(id) {
          this.$axios.post('/api/services/hzsfjtai/api/delete', {
            id:id
          }).then(res => {
            if (res.data.code === 200) {
                this.fetchData();
                this.$message({
                  type: 'success',
                  message: 'API删除成功!'
                });
            } else {
              this.$message(res.data.msg)
            }
          }).catch(err => {
            this.$message.error(err)
          })
        },
        // 过滤API
        filterApis() {
          if (!this.searchKeyword) {
            this.filteredApis = [...this.apis];
            return;
          }
          
          const keyword = this.searchKeyword.toLowerCase();
          this.filteredApis = this.apis.filter(api => {
            return api.apiName.toLowerCase().includes(keyword) || 
                   api.apiUrl.toLowerCase().includes(keyword) || 
                   (api.description && api.description.toLowerCase().includes(keyword)) ||
                   api.apiType.toLowerCase().includes(keyword);
          });
        },
        
        // 格式化日期
        formatDate(isoString) {
          const date = new Date(isoString);
          return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`;
        },
        
        // 生成唯一ID
        generateId() {
          return Math.max(0, ...this.apis.map(a => a.id)) + 1;
        }
      }
}
</script>
<style scoped lang="less" >
 .app-container {
      margin: 0 auto;
      padding: 20px;
    }
    
    .header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 20px;
      padding-bottom: 15px;
      border-bottom: 1px solid #ebeef5;
    }
    
    .header h1 {
      color: #303133;
      font-weight: 600;
      font-size: 24px;
      display: flex;
      align-items: center;
      gap: 10px;
    }
    
    .header h1 i {
      color: #409EFF;
    }
    
    .search-bar {
      display: flex;
      gap: 10px;
      margin-bottom: 20px;
    }
    
    .search-bar .el-input {
      flex: 1;
    }
    
    .el-table {
      border-radius: 8px;
      box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
      margin-bottom: 20px;
    }
    
    .el-table__row {
      cursor: pointer;
      transition: background-color 0.3s;
    }
    
    .el-table__row:hover {
      background-color: #f0f7ff !important;
    }
    
    .operation-cell {
      display: flex;
      gap: 8px;
    }
    
    .el-button--primary {
      background-color: #409EFF;
      border-color: #409EFF;
    }
    
    .el-button--primary:hover {
      background-color: #66b1ff;
      border-color: #66b1ff;
    }
    
    .el-button--primary:active {
      background-color: #3a8ee6;
      border-color: #3a8ee6;
    }
    
    .el-tag {
      border-radius: 12px;
      padding: 0 12px;
      height: 28px;
      line-height: 28px;
      margin-right: 6px;
      margin-bottom: 4px;
    }
    
    .el-tag--primary {
      background-color: #ecf5ff;
      border-color: #d9ecff;
      color: #409EFF;
    }
    
    .el-tag--success {
      background-color: #f0f9eb;
      border-color: #e1f3d8;
      color: #67c23a;
    }
    
    .no-data {
      text-align: center;
      padding: 40px 0;
      color: #909399;
    }
    
    .no-data i {
      font-size: 60px;
      color: #dcdfe6;
      margin-bottom: 15px;
    }
    
    .no-data p {
      font-size: 16px;
    }
    
    .el-dialog__header {
      border-bottom: 1px solid #ebeef5;
      padding: 15px 20px;
    }
    
    .el-dialog__title {
      color: #303133;
      font-weight: 600;
      font-size: 18px;
    }
    
    .el-dialog__body {
      padding: 20px;
      max-height: 70vh;
      overflow-y: auto;
    }
    
    .footer {
      text-align: center;
      padding: 20px 0;
      color: #909399;
      font-size: 14px;
    }
    
    .footer a {
      color: #409EFF;
      text-decoration: none;
    }
    
    .footer a:hover {
      text-decoration: underline;
    }
    
    /* 表单样式 */
    .form-section {
      margin-bottom: 20px;
      padding: 15px;
      border-radius: 8px;
      background: #f9fbfd;
      border: 1px solid #ebeef5;
    }
    
    .form-section-title {
      font-size: 16px;
      font-weight: 600;
      color: #409EFF;
      margin-bottom: 15px;
      display: flex;
      align-items: center;
      gap: 8px;
    }
    
    .project-tree {
      max-height: 300px;
      overflow-y: auto;
      border: 1px solid #ebeef5;
      border-radius: 4px;
      padding: 10px;
    }
    
    .project-tags {
      display: flex;
      flex-wrap: wrap;
      gap: 8px;
      margin-top: 10px;
    }
    
    .api-type-badge {
      display: inline-block;
      padding: 4px 12px;
      border-radius: 4px;
      font-size: 12px;
      font-weight: bold;
      text-transform: uppercase;
    }
    
    .api-type-get {
      background-color: #e6f7ff;
      color: #1890ff;
      border: 1px solid #91d5ff;
    }
    
    .api-type-post {
      background-color: #f6ffed;
      color: #52c41a;
      border: 1px solid #b7eb8f;
    }
    
    .api-type-put {
      background-color: #fff7e6;
      color: #fa8c16;
      border: 1px solid #ffd591;
    }
    
    .api-type-delete {
      background-color: #fff1f0;
      color: #f5222d;
      border: 1px solid #ffa39e;
    }
    
    .api-url {
      color: #1890ff;
      font-family: monospace;
      font-size: 14px;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }
    
    .api-url:hover {
      text-decoration: underline;
      color: #096dd9;
    }
    
    .api-icon {
      width: 40px;
      height: 40px;
      display: flex;
      align-items: center;
      justify-content: center;
      background: #ecf5ff;
      border-radius: 50%;
      color: #409EFF;
      font-size: 18px;
      margin-right: 12px;
    }
    
    .api-header {
      display: flex;
      align-items: center;
      margin-bottom: 8px;
    }
    
    .api-title {
      font-weight: 600;
      font-size: 16px;
      color: #303133;
    }
    
    .api-meta {
      color: #606266;
      font-size: 13px;
      display: flex;
      gap: 15px;
    }
    
    .api-meta-item {
      display: flex;
      align-items: center;
      gap: 4px;
    }
    
    .api-description {
      color: #606266;
      font-size: 14px;
      margin-top: 8px;
    }
</style>

